﻿using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UIWindows.Domains;
using UIWindows.Enums;
using UIWindows.GlobalStatics;
using UIWindows.Models;
using XingLucifer.IBase.Enums;
using Kinlo.Entitys;
using NPOI.XSSF.UserModel;

namespace UIWindows.Tools.Helper
{
    public class ExportHelper
    {
        public static bool Export_ProductionData(string path, XCode.Expression expression, ObservableCollection<DisplayItemsModel> displayItems)
        {
			try
			{
                IList<ProductionData> datas = ProductionData.FindAll(expression);
                NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
                ISheet sheet = book.CreateSheet("Sheet1");//获取第一个工作薄
                int rowCount = 0;
                int countSender = 0;
                IRow row = sheet.CreateRow(rowCount);
                var plist = displayItems.Where(x => x.IsOutput);
                int length = plist.Count();
                for (int i = 0; i < length; i++) row.CreateCell(i, CellType.String);
                foreach (var sender in plist.Select(x => x.Description))
                {
                    row.Cells[countSender].SetCellValue(sender);
                    countSender += 1;
                }
                rowCount += 1;
                foreach (var item in datas)
                {
                    row = sheet.CreateRow(rowCount);
                    for (int i = 0; i < length; i++) row.CreateCell(i, CellType.String);
                    countSender = 0;
                    try
                    {
                        foreach (var item1 in plist)
                        {

                            switch (item1.DataType)
                            {
                                case "无类型":
                                    row.Cells[countSender].SetCellValue($"{item[item1.Name]}");
                                    break;
                                case "浮点型":
                                    row.Cells[countSender].SetCellValue($"{item[item1.Name]:F2}");
                                    break;
                                case "时间型":
                                    long lvalue = (long)item[item1.Name];
                                    if (lvalue > 0)
                                    {
                                        row.Cells[countSender].SetCellValue($"{lvalue.GetDateTime():yyyy-MM-dd HH:mm:ss}");
                                    }
                                    else
                                    {
                                        row.Cells[countSender].SetCellValue("0000-00-00 00:00:00");
                                    }
                                    break;
                            }
                            countSender += 1;

                        }
                    }
                    catch (Exception ex)
                    {
                        $"数据导出异常：{ex.Message}".RunLog(MessageLevelType.错误);
                    }
                    rowCount += 1;
                }
                //导出excel
                if (!Directory.Exists(Path.GetDirectoryName(path))) { Directory.CreateDirectory(Path.GetDirectoryName(path)); }
                using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
                {
                    book.Write(fs);
                }
                book.Close();
                return true;
            }
			catch (Exception ex)
			{
                $"数据导出异常：{ex}".RunLog(MessageLevelType.错误);
			}
            return false;
        }


        public static bool Export_ProductionData_xls(string path, XCode.Expression expression, ObservableCollection<DisplayItemsModel> displayItems)
        {
            try
            {
                IList<ProductionData> datas = ProductionData.FindAll(expression);
                NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
                ISheet sheet = book.CreateSheet("Sheet1");//获取第一个工作薄
                int rowCount = 0;
                int countSender = 0;
                IRow row = sheet.CreateRow(rowCount);
                var plist = displayItems.Where(x => x.IsOutput);
                int length = plist.Count();
                for (int i = 0; i < length; i++) row.CreateCell(i, CellType.String);
                foreach (var sender in plist.Select(x => x.Description))
                {
                    row.Cells[countSender].SetCellValue(sender);
                    countSender += 1;
                }
                rowCount += 1;
                foreach (var item in datas)
                {
                    row = sheet.CreateRow(rowCount);
                    for (int i = 0; i < length; i++)
                        row.CreateCell(i, CellType.String);
                    countSender = 0;
                    foreach (var item1 in plist)
                    {
                        try
                        {
                            switch (item1.DataType)
                            {
                                case "无类型":
                                    row.Cells[countSender].SetCellValue($"{item[item1.Name]}");
                                    break;
                                case "浮点型":
                                    //row.Cells[countSender].SetCellValue($"{item[item1.Name]:F2}");
                                    row.Cells[countSender].SetCellValue($"{item[item1.Name]}");
                                    break;
                                //case "时间型":
                                //    long lvalue = (long)item[item1.Name];
                                //    if (lvalue > 0)
                                //    {
                                //        row.Cells[countSender].SetCellValue($"{lvalue.GetDateTime():yyyy-MM-dd HH:mm:ss}");
                                //    }
                                //    else
                                //    {
                                //        row.Cells[countSender].SetCellValue("0000-00-00 00:00:00");
                                //    }
                                //    break;
                                case "时间型":
                                    object rawValue = item[item1.Name];

                                    long lvalue = rawValue != null ? Convert.ToInt64(rawValue) : 0;

                                    if (lvalue > 0)
                                    {
                                        row.Cells[countSender].SetCellValue($"{lvalue.GetDateTime():yyyy-MM-dd HH:mm:ss}");
                                    }
                                    else
                                    {

                                        row.Cells[countSender].SetCellValue("0001-01-01 00:00:00");
                                    }
                                    break;
                                default:
                                    row.Cells[countSender].SetCellValue($"{item[item1.Name]}");
                                    break;
                            }

                        }
                        catch (Exception ex)
                        {
                            row.Cells[countSender].SetCellValue($"{item[item1.Name]}");
                            $"数据导出异常：{ex.Message}".RunLog(MessageLevelType.错误);
                        }
                        finally
                        {
                            countSender += 1;
                        }
                    }
                    rowCount += 1;
                }
                //导出excel
                if (!Directory.Exists(Path.GetDirectoryName(path))) { Directory.CreateDirectory(Path.GetDirectoryName(path)); }
                using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
                {
                    book.Write(fs);
                }

                book.Close();
                return true;
            }
            catch (Exception ex)
            {
                $"数据导出异常：{ex}".RunLog(MessageLevelType.错误);
            }
            return false;
        }
        public static bool Export_ProductionData_xlsx(string path, XCode.Expression expression, ObservableCollection<DisplayItemsModel> displayItems)
        {
            try
            {
                IList<ProductionData> datas = ProductionData.FindAll(expression);
                //NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
                //ISheet sheet = book.CreateSheet("Sheet1");//获取第一个工作薄

                IWorkbook book = new XSSFWorkbook(); // 使用 XSSFWorkbook 代替 xlsx 格式
                ISheet sheet = book.CreateSheet("Sheet1");
                int rowCount = 0;
                int countSender = 0;
                IRow row = sheet.CreateRow(rowCount);
                var plist = displayItems.Where(x => x.IsOutput);
                int length = plist.Count();
                for (int i = 0; i < length; i++) row.CreateCell(i, CellType.String);
                foreach (var sender in plist.Select(x => x.Description))
                {
                    row.Cells[countSender].SetCellValue(sender);
                    countSender += 1;
                }
                rowCount += 1;
                foreach (var item in datas)
                {
                    row = sheet.CreateRow(rowCount);
                    for (int i = 0; i < length; i++)
                        row.CreateCell(i, CellType.String);
                    countSender = 0;
                    foreach (var item1 in plist)
                    {
                        try
                        {
                            switch (item1.DataType)
                            {
                                case "无类型":
                                    row.Cells[countSender].SetCellValue($"{item[item1.Name]}");
                                    break;
                                case "浮点型":
                                    //row.Cells[countSender].SetCellValue($"{item[item1.Name]:F2}");
                                    row.Cells[countSender].SetCellValue($"{item[item1.Name]}");
                                    break;
                                //case "时间型":
                                //    long lvalue = (long)item[item1.Name];
                                //    if (lvalue > 0)
                                //    {
                                //        row.Cells[countSender].SetCellValue($"{lvalue.GetDateTime():yyyy-MM-dd HH:mm:ss}");
                                //    }
                                //    else
                                //    {
                                //        row.Cells[countSender].SetCellValue("0000-00-00 00:00:00");
                                //    }
                                //    break;

                                case "时间型":
                                    object rawValue = item[item1.Name];

                                    long lvalue = rawValue != null ? Convert.ToInt64(rawValue) : 0;

                                    if (lvalue > 0)
                                    {
                                        row.Cells[countSender].SetCellValue($"{lvalue.GetDateTime():yyyy-MM-dd HH:mm:ss}");
                                    }
                                    else
                                    {

                                        row.Cells[countSender].SetCellValue("0001-01-01 00:00:00");
                                    }
                                    break;
                                default:
                                    row.Cells[countSender].SetCellValue($"{item[item1.Name]}");
                                    break;
                            }

                        }
                        catch (Exception ex)
                        {
                            row.Cells[countSender].SetCellValue($"{item[item1.Name]}");
                            $"数据导出异常：{ex.Message}".RunLog(MessageLevelType.错误);
                        }
                        finally
                        {
                            countSender += 1;
                        }
                    }
                    rowCount += 1;
                }
                //导出excel
                if (!Directory.Exists(Path.GetDirectoryName(path))) { Directory.CreateDirectory(Path.GetDirectoryName(path)); }
                using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
                {
                    book.Write(fs, true);
                }

                book.Close();
                return true;
            }
            catch (Exception ex)
            {
                $"数据导出异常：{ex}".RunLog(MessageLevelType.错误);
            }
            return false;
        }
        public static bool Export_ProductionData_CSV(string path, XCode.Expression expression, ObservableCollection<DisplayItemsModel> displayItems)
        {
            try
            {
                IList<ProductionData> datas = ProductionData.FindAll(expression);

                using (StreamWriter sw = new StreamWriter(path, false, Encoding.UTF8))
                {
                    var plist = displayItems.Where(x => x.IsOutput).ToList();
                    int length = plist.Count();

                    // 写入表头
                    sw.WriteLine(string.Join(",", plist.Select(x => x.Description)));

                    // 写入数据
                    foreach (var item in datas)
                    {
                        var rowValues = new List<object>();

                        foreach (var item1 in plist)
                        {
                            try
                            {
                                if (item1.Description.Contains("测漏真空"))
                                {
                                    rowValues.Add($"{item[item1.Name]:F3}");
                                }
                                else
                                {
                                    switch (item1.DataType)
                                    {
                                        //case "无类型":
                                        case "浮点型":
                                            rowValues.Add($"{item[item1.Name]}");
                                            break;
                                        case "时间型":
                                            object rawValue = item[item1.Name];
                                            long lvalue = rawValue != null ? Convert.ToInt64(rawValue) : 0;

                                            if (lvalue > 0)
                                            {
                                                rowValues.Add($"{lvalue.GetDateTime():yyyy-MM-dd HH:mm:ss}");
                                            }
                                            else
                                            {

                                                rowValues.Add("0001-01-01 00:00:00");
                                            }
                                            break;
                                        default:
                                            rowValues.Add($"{item[item1.Name]}");
                                            //rowValues.Add($"\"{item[item1.Name]}\"");
                                            break;
                                    }
                                }

                            }
                            catch (Exception ex)
                            {
                                rowValues.Add($"{item[item1.Name]}");
                                $"数据导出异常：{ex.Message}".RunLog(MessageLevelType.错误);
                            }
                        }

                        // 将一行数据写入CSV
                        sw.WriteLine(string.Join(",", rowValues));
                    }
                }

                $"数据已导出至：{path}".RunLog(MessageLevelType.成功);
                return true;
            }
            catch (Exception ex)
            {
                $"数据导出异常：{ex}".RunLog(MessageLevelType.错误);
                return false;
            }
        }



    }
}
